package com.zookeeper.basic.one;

import org.apache.zookeeper.*;

import java.io.IOException;
import java.util.concurrent.CountDownLatch;

/**
 * Created by 58 on 2016-7-17.
 * 判断节点是否存在
 */
public class ZkExistSync implements Watcher {
    private static CountDownLatch countDownLatch = new CountDownLatch(1);
    private static ZooKeeper zooKeeper = null;
    public void process(WatchedEvent event) {
        try {
            if(Event.KeeperState.SyncConnected == event.getState()){
                if(Event.EventType.None == event.getType() && null == event.getType()){
                    System.out.println("-----------down......");
                    countDownLatch.countDown();
                }
                else  if(Event.EventType.NodeCreated == event.getType()){
                    System.out.println("Node("+event.getPath()+") Created");
                    zooKeeper.exists(event.getPath(),true);   //再次注册watcher
                }else if(Event.EventType.NodeDeleted == event.getType()){
                    System.out.println("Node("+event.getPath()+") Delete");
                    zooKeeper.exists(event.getPath(),true);
                }else if(Event.EventType.NodeDataChanged == event.getType()){
                    System.out.println("Node("+event.getPath()+") DataChanged");
                    zooKeeper.exists(event.getPath(),true);
                }
            }else {
                System.out.println("------------s--------------------");
            }
        }catch (Exception e){

        }
    }

    public static void main(String[] args) throws IOException, InterruptedException, KeeperException {
        String path = "/zk-bookx";
        System.out.println("------------1");
        ZooKeeper zooKeeper = new ZooKeeper("127.0.0.1:2181",5000,new ZkExistSync());
        //countDownLatch.await();
        System.out.println("------------2");
        zooKeeper.exists(path,true);
        System.out.println("------------3");
        zooKeeper.create(path,"".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE,CreateMode.PERSISTENT);
        System.out.println("------------4");
        zooKeeper.setData(path,"123".getBytes(),-1);
        zooKeeper.create(path+"/c1","".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE,CreateMode.PERSISTENT);
        //zooKeeper.delete(path+"/c1",-1);
        //zooKeeper.delete(path,-1);
        System.out.println("------------5");
        //Thread.sleep(3000);
    }
}
